﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Warehouse.DataAccess
{
    public partial class PermissionInUser
    {
        #region Public Methods
        public void Delete()
        {
            using (WarehouseClassesDataContext context = new WarehouseClassesDataContext())
            {

                context.ExecuteCommand("Delete from [User] where ID={0}", this.ID);
            }
        }

        #endregion

        public static PermissionInUser[] GetPermissionsByDep(int depID)
        {
            using (WarehouseClassesDataContext context = new WarehouseClassesDataContext())
            {
                return context.ExecuteQuery<PermissionInUser>("exec dbo.proc_GetPermissionsByDep @DepartmentID =" + depID.ToString()).ToArray();
            }
        }

        public static PermissionInUser[] GetPermissionsByUser(int userID)
        {
            using (WarehouseClassesDataContext context = new WarehouseClassesDataContext())
            {
                return context.ExecuteQuery<PermissionInUser>("exec dbo.proc_GetPermissionsByUser @UserID =" + userID.ToString()).ToArray();
            }
        }

        public static void SavePermission(int targetID, string targetType, string permissions)
        {
            using (WarehouseClassesDataContext context = new WarehouseClassesDataContext())
            {
                context.ExecuteCommand("Delete from [PermissionInUser] where TargetID={0} and TargetType={1}", targetID, targetType);

                string[] ps = permissions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string p in ps)
                {
                    //PermissionInUser permission = new PermissionInUser();
                    //permission.TargetID = targetID;
                    //permission.TargetType = targetType[0];
                    //permission.PermissionID = int.Parse(p);
                    //context.PermissionInUsers.InsertOnSubmit(permission);
                    context.ExecuteCommand("insert into [PermissionInUser] values ({0},{1},{2})", targetID, targetType[0], p);
                }
                context.SubmitChanges();
            }
        }
    }
}
